package com.zhang.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    public String paymentTest1(Integer id){
        return "线程池:"+Thread.currentThread().getName()+"id: "+id;
    }
    //#########服务降级
    @HystrixCommand(fallbackMethod = "paymentTimeout_error",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")})
    public String paymentTimeout(Integer id){
        int time=5;
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + "id: " + id +"耗时(秒): " + time;
    }
    public static String paymentTimeout_error(Integer id){
        return "线程池: "+Thread.currentThread().getName() +"id: "+id+"，请求超时请稍后重试";
    }


    //##########服务熔断
    @HystrixCommand(fallbackMethod = "Errorrr",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value="true"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60"),
    })
    public String paymentClose(@PathVariable("id") Integer id){
      if(id<0){
              throw new RuntimeException("ID不能为负数");
      }
      // 相当于UUID.randomUUID().toString()
        String i= IdUtil.simpleUUID();
       return "请求成功"  + "id: " + id;
    }
    public static String Errorrr(@PathVariable("id") Integer id){
        return "请求错误 服务器崩了 稍后再来  id: "+id;
    }
}
